<template>
  <div class="select-seat-footer-container" :style="{ paddingBottom: `16px` }">
    <nut-cell v-if="selectedSeat.length > 0">
      <scroll-view :scroll-x="true">
        <div class="select-list">
          <div class="item" v-for="(item, index) in selectedSeat" :key="index">
            <div class="left">
              <div class="name">{{ item.seatNo }}</div>
              <div class="price">
                <nut-price
                  :price="formatPriceOrigin(item.areaId) / 100"
                  style="color: #5232b7"
                  size="small"
                  :decimal-digits="2"
                  :thousands="true"
                />
              </div>
            </div>
            <div class="right" @click="onCloseItem(item)">
              <CircleClose color="#858a99" size="0.6rem"></CircleClose>
            </div>
          </div>
        </div>
      </scroll-view>
    </nut-cell>
    <div class="btns">
      <nut-button
        v-if="selectedSeat.length > 0"
        block
        type="primary"
        @click="onConfirm"
        color="linear-gradient(to right, #5232B7,#7237BC)"
        >￥{{ totalPriceNum }} 确认选座(原价格)</nut-button
      >
      <nut-button
        v-else
        block
        type="primary"
        color="linear-gradient(to right, #5232B7,#7237BC)"
        >请选择座位</nut-button
      >
    </div>
  </div>

</template>
<script setup lang="ts">
import { CircleClose } from "@nutui/icons-vue-taro";
import Taro from "@tarojs/taro";
import { onMounted, computed, toRefs, ref } from "vue";
const PriceVisible = ref(false);
const props = defineProps({
  selectedSeat: {
    type: Array<any>,
    default: [],
  },
  arealist: {
    type: Array<any>,
    default: [],
  },
  seatList: {
    type: Array<any>,
    default: [],
  },
  currentShowInfo: {
    type: Object,
    required: true,
  },
  currentShowId: {
    type: String,
    required: true,
  },
  rateList: {
    type: Array,
    required: true,
  },
});
const {
  selectedSeat,
  arealist,
  currentShowId,
  seatList,
  rateList,
  currentShowInfo,
} = toRefs(props);
onMounted(() => {
  // setBottomDistance();
  PriceVisible.value = false;
});
// 校验手机号
const onConfirmPriceRule = () => {
  try {
    const area_arr = selectedSeat.value.map((item) => {
      return item.areaId;
    });
    const abc = isRepeat(area_arr);
    if (!abc) {
      Taro.showToast({
        title: "请选择同一价格的座位，暂不支持跨区域选座~~",
        icon: "none",
        duration: 2000,
      });

      return;
    }
    let result = selectedSeat.value.every(function (element, index, array) {
      return checkSeat(element);
    });
    // 开始计算是否留下空位 ------------ 结束
    if (!result) {
      // 如果 result 为false
      Taro.showToast({
        title: "请不要留下空座位哦~",
        icon: "none",
      });
      return;
    }
    const resultInfo = {
      rateList: rateList.value,
      selectedSeat: selectedSeat.value,
      arealist: arealist.value,
      currentShowId: currentShowId.value,
      seatList: seatList.value, //
      currentShowInfo: currentShowInfo.value,
    };
    Taro.navigateTo({
      url: `/pages/order-channel/index?resultInfo=${encodeURIComponent(
        JSON.stringify(resultInfo)
      )}`,
    });

    PriceVisible.value = false;
    return;
  } catch (e) {
    console.log(e);
  }
};

const onConfirm = () => {
  onConfirmPriceRule()
};
// 检查每个座位是否会留下空位
const checkSeat = (element) => {
  // 标准为 1.左右侧都必须保留 两格座位 + 最大顺延座位(也就是已选座位减去自身)
  // 2.靠墙和靠已售的座位一律直接通过
  const checkNum = 2 + selectedSeat.value.length - 1;
  const gRowBasic = element.gRow;
  const gColBasic = element.gCol;
  let otherLoveSeatIndex = element.seatType;
  if (otherLoveSeatIndex) {
    // 如果是情侣座 不检测
    return true;
  }
  // 检查座位左侧
  let left = checkSeatDirection(gRowBasic, gColBasic, checkNum, "-");
  // 如果左侧已经检查出是靠着过道直接 返回true
  if (left === "special") {
    return true;
  }
  // 检查座位右侧
  let right = checkSeatDirection(gRowBasic, gColBasic, checkNum, "+");
  if (right === "special") {
    // 无论左侧是否是什么状态 检查出右侧靠着过道直接 返回true
    return true;
  } else if (right === "normal" && left === "normal") {
    // 如果左右两侧都有富裕的座位 返回true
    return true;
  } else if (right === "fail" || left === "fail") {
    // 如果左右两侧都是不通过检测 返回false
    return false;
  }
  return true;
};
// 检查左右侧座位满足规则状态
const checkSeatDirection = (gRowBasic, gColBasic, checkNum, direction) => {
  // 空位个数
  let emptySeat = 0;
  let x = 1; // 检查位置 只允许在x的位置出现过道,已售,维修
  for (let i = 1; i <= checkNum; i++) {
    let iter; // 根据 gRow gCol direction 找出检查座位左边按顺序排列的checkNum
    if (direction === "-") {
      iter = seatList.value.find(
        (el) => el.gRow == gRowBasic && el.gCol == gColBasic - i
      );
    } else if (direction === "+") {
      iter = seatList.value.find(
        (el) => el.gRow == gRowBasic && el.gCol == gColBasic + i
      );
    }
    if (x === i) {
      if (iter === undefined) {
        // 过道
        return "special";
      }
      if (iter.nowIcon === iter.soldedIcon || iter.nowIcon === iter.fixIcon) {
        // 已售或者维修
        return "special";
      }
      if (iter.nowIcon === iter.selectedIcon) {
        // 已选 顺延一位
        x++;
        continue;
      }
    } else {
      if (iter === undefined) {
        // 过道
        return "fail";
      }
      if (
        iter.nowIcon === iter.soldedIcon ||
        iter.nowIcon === iter.fixIcon ||
        iter.nowIcon === iter.selectedIcon
      ) {
        // 已售或者维修
        return "fail";
      }
    }
    emptySeat++;
    if (emptySeat >= 2) {
      return "normal";
    }
  }
};
const changeTwoDecimal = (x) => {
  let resNum = parseFloat(x);
  // isNaN()，判断一个变量是否为非数字的类型，非数字返回true，数字则返回false
  // console.log('你看=', isNaN(resNum))
  if (isNaN(resNum)) {
    return false;
  }
  resNum = Math.round(resNum * 100) / 100;
  return resNum;
};

const emit = defineEmits(["onCloseItem"]);
const onCloseItem = (item) => {
  emit("onCloseItem", item);
};
const formatPrice: any = computed(() => {
  return (id) => {
    return getPrice(id);
  };
});
const formatPriceOrigin: any = computed(() => {
  return (id) => {
    return getOrPrice(id);
  };
});
const totalPriceNum: any = computed(() => {
  // return selectedSeat.value.reduce((c1, c2) => c1 + parseFloat(c2.price), 0);
  let resPrice = 0;
  selectedSeat.value.forEach((item) => {
    const itemPrice = getOrPrice(item.areaId);
    resPrice = Number(resPrice) + Number(itemPrice);
  });
  return (resPrice / 100).toFixed(2);
});
const totalPickupPrice: any = computed(() => {
  // return selectedSeat.value.reduce((c1, c2) => c1 + parseFloat(c2.price), 0);
  let resPrice = 0;
  selectedSeat.value.forEach((item) => {
    const itemPrice = getPrice(item.areaId);
    resPrice = Number(resPrice) + Number(itemPrice);
  });
  return (resPrice / 100).toFixed(2);
});
const getPrice = (id) => {
  if (arealist.value.length === 0) {
    // 无分区
    // return Number(res.price);
  } else {
    // 有分区
    const res = arealist.value.find((item) => {
      return item.regionName == id;
    });
    return Number(res.pickUpPrice);
  }
};
const getOrPrice = (id) => {
  if (arealist.value.length === 0) {
    // 无分区
    // return Number(res.price);
  } else {
    // 有分区
    const res = arealist.value.find((item) => {
      return item.regionName == id;
    });
    return Number(res.price);
  }
};
const isRepeat = (arr) => {
  let res = true;
  const frist_item = arr[0];
  for (var i in arr) {
    if (!(arr[i] === frist_item)) {
      res = false;
    }
  }
  return res;
};
</script>
<style lang="scss">
.select-seat-footer-container {
  .nut-radio-group .nut-radio-group--horizontal {
    .nut-radio .nut-radio--round {
      .nutui-iconfont .nut-icon .nut-icon-check-checked .nut-radio__icon {
        background-color: #5232b7 !important;
      }
    }
  }

  display: flex;
  flex-direction: column;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 0 25px;
  .radio-box {
    display: flex;
    align-items: center;
  }

  .select-list {
    display: flex;
    flex-direction: row;

    .item {
      background: #f6f8f9;
      display: flex;
      flex-direction: row;
      padding: 10px 20px;
      margin-right: 20px;
      border-radius: 10px;

      .left {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        width: 120px;

        .name {
          font-size: 24px;
          color: #858a99;
        }

        .price {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;

          .nut-price {
            display: flex;
          }
        }
      }

      .right {
        padding: 0 10px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
      }
    }
  }
}
</style>
